package com.bwstudio.common.response;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * 分页响应体的基类，
 * 使用时继承此基类，填充数据List，并给PageDTO计算对应的值
 * @param <T>
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PageResult<T> {

    private Collection<T> rows;

    /**
     * 当前页码
     */
    private int pageNo;

    /**
     * 当前单页的记录数
     */
    private int pageSize;

    public void setPageSize(int pageSize) {
        if (pageSize < 1) {
            this.pageSize = 1;
        } else {
            this.pageSize = pageSize;
        }

    }

    /**
     * 总记录数
     */
    private int totalRows;

    /**
     * 总页数
     */
    private int totalPages;

    public int getTotalPages() {
        return this.totalRows % this.pageSize == 0 ? this.totalRows
                / this.pageSize : (this.totalRows / this.pageSize) + 1;
    }

    public boolean isEmpty() {
        return this.rows == null || this.rows.size() == 0;
    }

    public boolean isNotEmpty() {
        return !this.isEmpty();
    }

    public static <T> PageResult<T> of(Collection<T> data, int totalRows, int pageNo, int pageSize) {
        PageResult<T> pageResult = new PageResult();
        pageResult.setRows(data);
        pageResult.setTotalRows(totalRows);
        pageResult.setPageSize(pageSize);
        pageResult.setPageNo(pageNo);
        return pageResult;
    }

}
